#!/usr/bin/env python
# -*- coding: utf-8 -*-
# python3
# sendEmail.py
# author: ycf
'''''
使用python写邮件 smtp服务的tls模式
'''

import smtplib
import imaplib
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import email.errors

def smtpPostMail(sender = '', password = '', senderName = '', sendTo = '', subject = '',message = '', files = ()):
    SMTPserver = 'smtp.163.com'
    SMTPserverPort = 465
    msg = MIMEMultipart()

    msg['Subject'] = subject
    msg['From'] = senderName
    msg['To'] = sendTo

    # 登录
    # mailserver = smtplib.SMTP(SMTPserver, 25)
    mailserver = smtplib.SMTP_SSL(SMTPserver + str(SMTPserverPort))
    # mailserver.set_debuglevel(1)
    mailserver.login(sender, password)

    #载体段
    textMsg = MIMEText(message)

    #文本段
    msg.attach(textMsg)

    #文件段
    for filePath in files:
        if os.path.exists(filePath) and os.path.isfile(filePath):
            file = open(filePath, 'rb')
            fileDataToEmail = MIMEApplication(file.read())
            fileDataToEmail.add_header('Content-Disposition', 'attachment', filename=file.name)
            msg.attach(fileDataToEmail)

    #开始发送
    mailserver.sendmail(sender, [sendTo], msg.as_string())
    mailserver.quit()
    print('send email %s' %(message))

if __name__ == '__main__':
    #构造目录集合
    path = r'E:\Temp'
    files = os.listdir(path)
    filelist = []
    for i in files:
        filelist.append(path+r'/'+i)

    #发送文件和信息
    smtpPostMail(sender = 'sender', password = 'password',senderName = 'name', sendTo = 'sendto',subject = 'sended By Python Script!!!', message = 'Test Send　Files By Python From ** To ** Mail Box。。。', files = filelist)